#!/usr/bin/env python
# encoding: utf-8
"""
@author:zwb
@file: links.py
@contact: zwb15083976291@163.com
@time: 2021/11/21
"""
import os

from django.utils.decorators import method_decorator

from admin.serializers.links import LinkSerializer, CreateLinkSerializer, DeleteLinkSerializer, PutLinkSerializer
from common.models import BlogLink
from utils.filters.views_filters import SearchLinksFilter
from utils.responses import CommonResponse, CommonAPIResponseStatus
from utils.serializers.serializer import PaginatorSerializer
from utils.user_authentication import allow_admin_user
from utils.views import BasePaginateGenericAPIView
import logging

logger = logging.getLogger("default")


@method_decorator(allow_admin_user, name='dispatch')
class ManagementLinkView(BasePaginateGenericAPIView):
    diff_methods_request_params = dict(
        get=dict(optional=['pageNum', 'pageSize', 'search'], defualt_value=dict(pageNum=1, pageSize=10)),
        post=dict(required=['link_name', 'link_image_url', 'link_url', 'desc']),
        delete=dict(required=['id']),
        put=dict(required=['id', 'link_name', 'link_image_url', 'link_url', 'desc']))

    diff_methods_serializer_class = dict(get=PaginatorSerializer, post=CreateLinkSerializer,
                                         delete=DeleteLinkSerializer,
                                         put=PutLinkSerializer)
    filter_backends = [SearchLinksFilter]

    def get(self, request):
        ret, message = self.validate_request_params()
        if not ret:
            return CommonResponse(CommonAPIResponseStatus.BAD_REQUEST, message=message)
        query_set = self.filter_queryset(BlogLink.objects.order_by("-create_time"))
        paginator, models = self.paginate_queryset(query_set, self.serializer.validated_data)
        return CommonResponse(data=self.get_paginated_response(self.serializer.validated_data, paginator,
                                                               LinkSerializer(instance=models,
                                                                              many=True).data))

    def post(self, request):
        ret, message = self.validate_request_params()
        if not ret:
            return CommonResponse(CommonAPIResponseStatus.BAD_REQUEST, message=message)
        self.serializer.save()
        return CommonResponse(data=self.serializer.data)

    def delete(self, request):
        ret, message = self.validate_request_params()
        if not ret:
            return CommonResponse(CommonAPIResponseStatus.BAD_REQUEST, message=message)
        self.serializer.select_field_delete_obj()
        return CommonResponse(message='删除成功', data=self.serializer.data)

    def put(self, request):
        ret, message = self.validate_request_params()
        if not ret:
            return CommonResponse(CommonAPIResponseStatus.BAD_REQUEST, message=message)
        self.serializer.select_field_update_obj()
        return CommonResponse(message='修改成功', data=self.serializer.data)
